/*
 * Copyright (C) 2015 Bilibili
 * Copyright (C) 2015 Zhang Rui <bbcallen@gmail.com>
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.living.player.services;

import android.app.Application;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.media.AudioManager;
import android.os.Handler;
import android.os.IBinder;
import android.os.Looper;
import android.util.Log;

import com.living.player.event.EventStatusPause;
import com.living.player.event.EventStatusPlay;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;

import androidx.annotation.MainThread;
import androidx.annotation.Nullable;

import tv.danmaku.ijk.media.exo.IjkExoMediaPlayer;
import tv.danmaku.ijk.media.player.IMediaPlayer;

/**
 * 音频后台 播放服务
 * intentToStop(Context context)    context.stopService(newIntent(context));
 */
public class MediaPlayerService extends Service {
    protected static IMediaPlayer sMediaPlayer;
    protected static Application application;
    protected Handler mainThreadHandler = new Handler(Looper.getMainLooper());

    private static IMediaPlayer.OnPreparedListener mOnPreparedListener;
    private static IMediaPlayer.OnCompletionListener mOnCompletionListener;
    private static IMediaPlayer.OnErrorListener mOnErrorListener;

    public static Intent newIntent(Context context) {
        Intent intent = new Intent(context, MediaPlayerServiceImp.class);
        return intent;
    }

    public static void intentToStart(Context context) {
        context.startService(newIntent(context));
    }

    public static void setMediaPlayer(IMediaPlayer mp) {
        if (sMediaPlayer != null && sMediaPlayer != mp) {
            if (sMediaPlayer.isPlaying())
                sMediaPlayer.stop();
            sMediaPlayer.release();
            sMediaPlayer = null;
        }
        if (mp != null) {
            sMediaPlayer = mp;
            sMediaPlayer.setOnPreparedListener(mPreparedListener);
            sMediaPlayer.setOnCompletionListener(mCompletionListener);
            sMediaPlayer.setOnErrorListener(mErrorListener);
        }
    }

    public static void setOnPreparedListener(IMediaPlayer.OnPreparedListener l) {
        mOnPreparedListener = l;
    }

    public static void setOnCompletionListener(IMediaPlayer.OnCompletionListener l) {
        mOnCompletionListener = l;
    }

    public static void setOnErrorListener(IMediaPlayer.OnErrorListener l) {
        mOnErrorListener = l;
    }

    private static IMediaPlayer.OnPreparedListener mPreparedListener = new IMediaPlayer.OnPreparedListener() {
        public void onPrepared(IMediaPlayer mp) {
//            mPrepareEndTime = System.currentTimeMillis();
//            mCurrentState = STATE_PREPARED;
            if (mOnPreparedListener != null) {
                mOnPreparedListener.onPrepared(mp);
            }
        }
    };

    private static IMediaPlayer.OnCompletionListener mCompletionListener = new IMediaPlayer.OnCompletionListener() {
        public void onCompletion(IMediaPlayer mp) {
//                    mCurrentState = STATE_PLAYBACK_COMPLETED;
//                    mTargetState = STATE_PLAYBACK_COMPLETED;
            MediaPlayerServiceImp.onPlayComplete(mp);
            if (mOnCompletionListener != null) {
                mOnCompletionListener.onCompletion(mp);
            }
        }
    };

    private static IMediaPlayer.OnErrorListener mErrorListener = new IMediaPlayer.OnErrorListener() {
        public boolean onError(IMediaPlayer mp, int framework_err, int impl_err) {
//            Log.d(TAG, "Error: " + framework_err + "," + impl_err);
            MediaPlayerServiceImp.onPlayCompleteError(mp);
            if (mOnErrorListener != null) {
                if (mOnErrorListener.onError(mp, framework_err, impl_err)) {
                    return true;
                }
            }
            return true;
        }
    };

    private static IMediaPlayer.OnInfoListener mInfoListener = new IMediaPlayer.OnInfoListener() {
        public boolean onInfo(IMediaPlayer mp, int arg1, int arg2) {
//                    if (mOnInfoListener != null) {
//                        mOnInfoListener.onInfo(mp, arg1, arg2);
//                    }
            return true;
        }
    };


    @Override
    public void onCreate() {
        super.onCreate();
        application = getApplication();
        //进行EventBus的注册
        EventBus.getDefault().register(this);
    }

    @Subscribe
    public void onEvent(Object event) {
        onEventRev(event);
    }

    protected void onEventRev(Object event) {
        // todo nothing
    }

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }

    public static IMediaPlayer getMediaPlayer() {
        return sMediaPlayer;
    }

    public static void startPlay() {
        if (isPlayable()) {
            sMediaPlayer.start();
            EventBus.getDefault().post(new EventStatusPlay());
        }
    }

    public static void pausePlay() {
        if (isPlaying() && sMediaPlayer != null) {
            sMediaPlayer.pause();
            EventBus.getDefault().post(new EventStatusPause());
        }
    }

    public static boolean isPlaying() {
        boolean isPlaying = false;
        if (sMediaPlayer != null) {
            isPlaying = sMediaPlayer.isPlaying();
        }
        return isPlaying;
    }

    public static boolean isPlayable() {
        boolean isPlayable = false;
        if (sMediaPlayer != null) {
            isPlayable = sMediaPlayer.isPlayable();
        }
        return isPlayable;
    }


}
